package math;

import java.util.*;

public class Scope 
{
    private SymbolTable symbolTable;
    private Scope parent;

    public Scope()
    {
        symbolTable = SymbolTable.getDefaultTable();
    }

    public Scope(Scope parent)
    {
        this.parent = parent;
        symbolTable = new SymbolTable();
    }

    public boolean contains(String s)
    {
        boolean result = symbolTable.contains(s);
        if(parent != null && result == false)
        {
            result = parent.contains(s);
        }
        return result;
    }

    public Symbol get(String s)
    {
        Symbol result = symbolTable.get(s);
        if(parent != null && result == null)
        {
            result = parent.get(s);
        }
        return result;
    }

    public void register(String name,Symbol symbol)
    {
        if(this.symbolTable.contains(name))
        {
            throw new IllegalStateException(name + " cannot be redefined in a same scope");
        }

        this.symbolTable.register(name,symbol);
    }

    public void registerAll(Map<String,Symbol> symbols)
    {
        for(Map.Entry<String,Symbol> symbol : symbols.entrySet())
        {
            String key = symbol.getKey();
            Symbol value = symbol.getValue();
            register(key,value);
        }
    }
}


